package com.xiaojitui.pro;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    //定义一个静态的list集合存储当前全部在线socket管道
    public static List<Socket> allOnlineSockets=new ArrayList<>();
    public static void main(String[] args) throws Exception {
        System.out.println("===========服务端启动成功==========");
        //1. 注册端口
        ServerSocket serverSocket=new ServerSocket(7777);
        while (true) {
            //2. 必须调用accept通信管道得到一个字节数输入流
            Socket socket=serverSocket.accept();
            System.out.println(socket.getRemoteSocketAddress()+"来了");
            allOnlineSockets.add(socket);// 上线
            System.out.println("当前在线人数："+allOnlineSockets.size());
            //3. 创建独立线程处理socket
            new ServerReaderThread(socket).start();
        }
    }
}

class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            //3. 从socket通信管道中得到一个字符输入流进行消息的接收
            InputStream is=socket.getInputStream();
            //4. 把字节输入流包装成字符输入流进行消息的接受
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            //5. 按照流程读取消息
            String msg;
            while ((msg= br.readLine())!=null){
                System.out.println(socket.getRemoteSocketAddress()+"说了: "+msg);
                //端口转发
                sendMasg(msg);
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress()+"老弟下线了。");
            Server.allOnlineSockets.remove(socket);
        }
    }

    private void sendMasg(String msg) throws Exception {
        for (Socket socket : Server.allOnlineSockets) {
            PrintStream ps=new PrintStream(socket.getOutputStream());
            ps.println(msg);
            ps.flush();
        }
    }
}